<template>
  <div class="profile-container">
    <!-- 个人信息卡片 -->
    <el-card class="profile-card">
      <div slot="header">
        <span class="card-header">个人信息</span>
      </div>
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <span class="username">{{ user.username }}</span>
        </el-form-item>
        <el-form-item label="身份">
          <span class="role">{{ user.isAdmin ? '管理员' : '普通用户' }}</span>
        </el-form-item>
        <el-form-item>
          <template v-if="user.isAdmin">
            <el-button type="primary" @click="$router.push('/admin')">管理系统</el-button>
          </template>
          <el-button type="primary" @click="showPasswordDialog = true">修改密码</el-button>
          <el-button type="danger" @click="handleLogout">退出登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      :visible.sync="showPasswordDialog"
      width="400px"
      @close="resetPasswordForm"
    >
      <el-form 
        :model="passwordForm" 
        :rules="passwordRules" 
        ref="passwordForm" 
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password" 
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword">确认修改</el-button>
      </div>
    </el-dialog>

    <!-- 管理员功能卡片 -->
    <el-card v-if="user.isAdmin" class="admin-functions-card">
      <div slot="header">
        <span class="card-header">销售统计</span>
      </div>
      <div class="chart-container">
        <div id="salesChart" style="width: 100%; height: 400px;"></div>
      </div>
    </el-card>

    <!-- 订单历史卡片 -->
    <el-card class="orders-card">
      <div slot="header">
        <span class="card-header">订单历史</span>
      </div>
      
      <div v-if="orders.length === 0" class="empty-orders">
        <i class="el-icon-document"></i>
        <p>暂无订单记录</p>
      </div>

      <el-timeline v-else>
        <el-timeline-item
          v-for="order in orders"
          :key="order.id"
          :timestamp="order.date"
          placement="top"
          :type="order.status === '已完成' ? 'success' : 'primary'"
        >
          <el-card class="order-card">
            <h4>订单编号: #{{ order.id }}</h4>
            <div class="order-items">
              <el-table
                :data="order.items"
                style="width: 100%"
                size="small"
              >
                <el-table-column prop="name" label="商品名称"></el-table-column>
                <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
                <el-table-column label="单价" width="100">
                  <template slot-scope="scope">
                    ¥{{ scope.row.price }}
                  </template>
                </el-table-column>
                <el-table-column label="小计" width="100">
                  <template slot-scope="scope">
                    ¥{{ scope.row.price * scope.row.quantity }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="order-footer">
              <span class="order-status">{{ order.status }}</span>
              <span class="order-total">总计: ¥{{ order.total }}</span>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'UserProfile',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.passwordForm.confirmPassword !== '') {
          this.$refs.passwordForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      showPasswordDialog: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
        ],
        newPassword: [
          { validator: validatePass, trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      chart: null
    }
  },
  computed: {
    user() {
      return this.$store.state.user
    },
    orders() {
      return this.$store.state.orders
    }
  },
  methods: {
    handleLogout() {
      this.$store.commit('setUser', null)
      localStorage.removeItem('user')
      this.$router.push('/login')
      this.$message.success('已退出登录')
    },
    handleChangePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          // 这里可以添加实际的密码修改逻辑
          this.$message.success('密码修改成功')
          this.showPasswordDialog = false
          this.resetPasswordForm()
        }
      })
    },
    resetPasswordForm() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      if (this.$refs.passwordForm) {
        this.$refs.passwordForm.clearValidate()
      }
    },
    initChart() {
  const chartDom = document.getElementById('salesChart');
  this.chart = echarts.init(chartDom);
  
  const option = {
    title: {
      text: '本周销售前三的菜品和酒水',  // 修改标题
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['东坡肉', '麻婆豆腐', '水煮鱼', '可乐', '飞天茅台', '机油'],  // 修改legend为具体菜品和酒水名称
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value',
      name: '销售额 (元)'
    },
    series: [
      {
        name: '东坡肉',
        type: 'line',
        smooth: true,
        data: [20, 40, 60, 60, 110, 180, 221],  // 东坡肉的销售数据
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '麻婆豆腐',
        type: 'line',
        smooth: true,
        data: [18, 40, 110, 150, 180, 220, 250],  // 麻婆豆腐的销售数据
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '水煮鱼',
        type: 'line',
        smooth: true,
        data: [15, 70, 160, 180, 190, 210, 220],  // 水煮鱼的销售数据
        itemStyle: {
          color: '#FF9E0D'
        }
      },
      {
        name: '可乐',
        type: 'line',
        smooth: true,
        data: [50, 130, 140, 160, 200, 210, 220],  // 可乐的销售数据
        itemStyle: {
          color: '#FF6A00'
        }
      },
      {
        name: '飞天茅台',
        type: 'line',
        smooth: true,
        data: [50, 51, 80, 150, 156, 180, 200],  // 飞天茅台的销售数据
        itemStyle: {
          color: '#C20000'
        }
      },
      {
        name: '机油',
        type: 'line',
        smooth: true,
        data: [80, 90, 100, 110, 120, 130, 150],  // 机油的销售数据
        itemStyle: {
          color: '#8C5F3D'
        }
      }
    ]
  }
  
  this.chart.setOption(option);

  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    this.chart && this.chart.resize();
  });
}
  },
  mounted() {
    this.$nextTick(() => {
      if (this.user.isAdmin) {
        this.initChart()
      }
    })
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  created() {
    // 从 URL 获取 tab 参数并设置到 Admin 页面
    if (this.$route.query.tab && this.user.isAdmin) {
      this.$router.push(`/admin?tab=${this.$route.query.tab}`)
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.profile-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-header::before {
  content: '';
  display: block;
  width: 4px;
  height: 20px;
  background: linear-gradient(45deg, #409EFF, #36D1DC);
  border-radius: 2px;
}

.username {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.empty-orders {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.empty-orders i {
  font-size: 48px;
  margin-bottom: 20px;
}

.order-card {
  margin-bottom: 10px;
}

.order-card h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.order-items {
  margin: 15px 0;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #EBEEF5;
}

.order-status {
  color: #67C23A;
  font-weight: bold;
}

.order-total {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.el-timeline {
  padding: 20px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }
  
  .el-timeline {
    padding: 10px;
  }
}

.el-dialog__body {
  padding: 20px 40px;
}

.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.role {
  font-size: 14px;
  background: linear-gradient(45deg, #409EFF, #36D1DC);
  -webkit-background-clip: text;
   background-clip: text; /* 添加标准属性 */
  -webkit-text-fill-color: transparent;
  font-weight: bold;
}

.admin-functions-card {
  margin-bottom: 20px;
}

.admin-functions {
  padding: 10px 0;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.function-item:hover {
  transform: translateY(-5px);
}

.function-item i {
  font-size: 30px;
  color: #409EFF;
  margin-bottom: 10px;
}

.function-item span {
  color: #606266;
  font-size: 14px;
}

.el-card.is-hover-shadow:hover {
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.chart-container {
  padding: 20px;
}
</style> 